# -*- coding: utf-8 -*-
"""
 @File    : rest.py
 @Time    : 2021/9/13
 @Author  : 包建强
 @Description    : restful服务
"""

import argparse
import base64
import itertools
import sys
import numpy as np
import tornado.httpserver
import tornado.wsgi
from flask import Flask, request
import json
from paddleocr import PaddleOCR
import cv2

import utils

app = Flask(__name__)
app.config["JSON_AS_ASCII"] = False


@app.route('/recognition', methods=['POST'])
def ocr_reg():
    # args = request.args.get("name") # 获取  get  参数
    # form = request.form.get('data') # 获取  post 参数

    image_path = request.form.get('image_path')

    list = []

    result = ocr.ocr(image_path, cls=True, det=True, rec=True)
    for subList in result:
        # xy1_x = subList[0][0][0]
        # xy1_y = subList[0][0][1]
        # xy2_x = subList[0][1][0]
        # xy2_y = subList[0][1][1]
        # xy3_x = subList[0][2][0]
        # xy3_y = subList[0][2][1]
        # xy4_x = subList[0][3][0]
        # xy4_y = subList[0][3][1]

        left = int(subList[0][0][0])
        top = int(subList[0][0][1])
        width = int(subList[0][2][0] - subList[0][0][0])
        height = int(subList[0][2][1] - subList[0][0][1])

        text = subList[1][0]
        accuracy = int(subList[1][1] * 100)

        entity = {
            'left': left,
            'top': top,
            'width': width,
            'height': height,
            'text': text,
            'accuracy': accuracy
        }

        list.append(entity)

    print(list)
    return {'paddle_result': list}


@app.route('/detect', methods=['POST'])
def ocr_detect():
    image_path = request.form.get('image_path')

    list = []

    result = ocr.ocr(image_path, cls=True, det=True, rec=False)
    for subList in result:
        left = int(subList[0][0])
        top = int(subList[0][1])
        width = int(subList[2][0] - subList[0][0])
        height = int(subList[2][1] - subList[0][1])

        entity = {
            'left': left,
            'top': top,
            'width': width,
            'height': height
        }

        list.append(entity)

    print(list)
    return {'paddle_result': list}

@app.route('/regregion', methods=['POST'])
def ocr_reg_region():
    left = int(request.form.get('left'))
    top = int(request.form.get('top'))
    width = int(request.form.get('width'))
    height = int(request.form.get('height'))
    image_path = request.form.get('image_path')

    img = cv2.imread(image_path)

    box = [[left,top],[left+width,top],[left+width,top+height],[left,top+height]]

    try:
        img_crop = utils.get_rotate_crop_image(img, np.array(box, np.float32))

        if img_crop is None:
            return {'error': '图片太小，不能识别！'}

        result = ocr.ocr(img_crop, cls=True, det=False, rec=True)
        if result[0][0] != '':
            return {
                'text': result[0][0],
                'accuracy': int(result[0][1] * 100)
            }

        else:
            return {'error': '识别不出！'}

    except Exception as ex:
        print(ex)





def start_tornado(app, port=5000):
    http_server = tornado.httpserver.HTTPServer(
        tornado.wsgi.WSGIContainer(app))
    http_server.listen(port)
    print("Tornado server starting on port {}".format(port))
    tornado.ioloop.IOLoop.instance().start()


if __name__ == '__main__':
    ocr = PaddleOCR(use_pdserving=False, use_angle_cls=True, det=True, cls=True, use_gpu=False, lang='ch')

    # 启动restful服务
    start_tornado(app, 5000)
